var crypto = require('crypto');

function encrypt(key, iv, data) {
    var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
    var crypted = cipher.update(data, 'utf8', 'binary');
    crypted += cipher.final('binary');
    crypted = new Buffer(crypted, 'binary');
    return crypted;
}

/**
 * 解密方法
 * @param key      解密的key
 * @param iv       向量
 * @param crypted  密文
 * @returns string
 */
function decrypt(key, iv,crypted) {
    crypted = new Buffer(crypted,'base64');
    let decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
    let decoded = decipher.update(crypted, 'binary', 'utf8');
    try {
        decoded += decipher.final('utf8');
        return { code:200,decoded:decoded};
    }catch (e){
        return { code:500 };
    }
}

let getMd5 = function (key) {
    let Md5key = key;
    let md5=crypto.createHash("md5");
    md5.update(Md5key);
    let strMac = md5.digest('hex');
    return strMac.substring(0,16);
};
let getMd5Nomal = function (key) {
    let Md5key = key;
    let md5=crypto.createHash("md5");
    md5.update(Md5key);
    let strMac = md5.digest('hex');
    return strMac;
};



let key = getMd5('chongdingzhushou123');
let vi = getMd5('cdzs!@#');

/**
 * @time {string}  注册时间
 * @MacId {string}   机器码
 * @aliveTime {string} 激活时间 （月）
 */
exports.encrypt = encrypt;
exports.decrypt = decrypt;
exports.getMd5 = getMd5;
exports.getMd5Nomal = getMd5Nomal;
exports.key = key;
exports.vi = vi;


